package com.wxg.my.d01;

public class DaemonPrinterV3 {

    public static void main(String[] args) {
        DaemonPrinterV3.forClass(DaemonPrinterV3.class)
                .interval(800)
                .run();

        for (int i = 0; i < 10; i++) {
            System.out.println(String.valueOf(System.currentTimeMillis()).substring(7));
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                break;
            }
        }

    }

    public static Inner forClass(Class<?> clazz) {
        inner.forClass(clazz);
        return inner;
    }

    private static Inner inner = new Inner();

    private static class Inner {
        private Class<?> clazz;
        private long interval;

        public void run() {

            final String _name = "Daemon-" + Thread.currentThread().getId();
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if (Thread.currentThread().isInterrupted()) {
                            System.out.println("Interrupted!");
                            break;
                        }

                        System.out.println(String.format("[%s] - [%s] - [%d]", _name,
                                clazz.getSimpleName(),
                                System.currentTimeMillis()));

                        try {
                            Thread.sleep(interval);
                        } catch (InterruptedException e) {
                            System.out.println("Interrupted When Sleep");
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            });
            thread.setDaemon(true);
            thread.start();
        }

        public Class<?> forClass() {
            return clazz;
        }

        public Inner forClass(Class<?> clazz) {
            this.clazz = clazz;
            return this;
        }

        public long interval() {
            return interval;
        }

        public Inner interval(long interval) {
            this.interval = interval;
            return this;
        }
    }

}
